#include "data.hpp"
// sock封装
class Sock
{
public:
    friend void Recv(std::unordered_map<int, Data_buffer *> *buffer, const epoll_event events);
    Sock() = default;
    int create()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            cout << strerror(errno) << endl;
            exit(1);
        }
        return _sock;
    }
    bool Bind()
    {
        sockaddr_in sever;
        sever.sin_addr.s_addr = INADDR_ANY;
        sever.sin_family = AF_INET;
        sever.sin_port = htons(8080);
        int ret = bind(_sock, (sockaddr *)(&sever), sizeof(sever));
        if (ret < 0)
        {
            cout << strerror(errno) << endl;
            exit(2);
        }
        return true;
    }
    void Listen()
    {
        int ret = listen(_sock, QUEUE_LISTEN);
        if (ret < 0)
        {
            cout << strerror(errno) << endl;
            exit(3);
        }
    }
    void Connect(int sock, string ip, uint16_t port)
    {
        sockaddr_in sever;
        sever.sin_addr.s_addr = inet_addr(ip.c_str());
        sever.sin_family = AF_INET;
        sever.sin_port = htons(port);
        int ret = connect(sock, (sockaddr *)(&sever), sizeof(sever));
        if (ret < 0)
        {
            cout << strerror(errno) << endl;
            exit(4);
        }
    }
    int Accept()
    {
        sockaddr_in client;
        socklen_t len = sizeof(client);
        int sock = accept(_sock, (sockaddr *)(&client), &len);
        if (sock < 0)
        {
            if (errno == EWOULDBLOCK || errno == EAGAIN)
                std::cout << "没数据，请再试一次" << std::endl;
            else if (errno == EINTR)
                std::cout << "被中断，请再试一次" << std::endl;
            else
                std::cout << "accept fail:" << strerror(errno) << std::endl;
        }
        return sock;
    }
    ~Sock()
    {
        if (_sock > 0)
            close(_sock);
    }

private:
    int _sock;
};
